//
//  CYCreditCacheTool.m
//  CreditAddressBook
//
//  Created by Lee on 15/5/10.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYCreditCacheTool.h"
#import "FMDB.h"
#import "CYDefaultRecordAO.h"
#import "MJExtension.h"

@implementation CYCreditCacheTool

static FMDatabaseQueue *_queue;

+ (void)initialize
{
    // 0.获得沙盒中的数据库文件名
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"defaultRecords.sqlite"];
    
    // 1.创建队列
    _queue = [FMDatabaseQueue databaseQueueWithPath:path];
    
    // 2.创表
    [_queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"create table if not exists t_defaultRecord (id integer primary key autoincrement, idstr text UNIQUE, access_token text, createTime text, name text, certificateNo text, phone text, defaultRecord blob);"];
    }];
}

/**
 *  缓存一条数据
 *
 *  @param dict 需要缓存的CYDefaultRecordAO数据
 */
+ (void)addDefaultRecord:(CYDefaultRecordAO *)defr {
    [_queue inDatabase:^(FMDatabase *db) {
        //需要存储的数据
        NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
        NSString *userName = [userDef objectForKey:CYUserNameKey];
        NSString *password = [userDef objectForKey:CYPasswordKey];
        NSString *access_token = nil;
        if (userName && password) {
            access_token = [password stringByAppendingString:userName];//用户唯一标识
        }else {
            access_token = @"visitor";
        }
        NSString *idstr = defr.defaultRecordId;
        NSString *createTime = defr.createTime;
        NSString *name = defr.name;
        NSString *certificateNo = defr.certificateNo;
        NSString *phone = defr.phone;
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:defr];
        //存数据
        [db executeUpdate:@"insert or replace into t_defaultRecord (idstr, access_token, createTime, name, certificateNo, phone, defaultRecord) values(?, ?, ?, ?, ?, ?, ?)", idstr, access_token, createTime,  name, certificateNo, phone, data];
    }];
}

/**
 *  缓存N条数据
 *
 *  @param dictArray 需要缓存的CYDefaultRecordAO数据
 */
+ (void)addDefaultRecords:(NSArray *)dictArray {
    for (CYDefaultRecordAO *dic in dictArray) {
        [self addDefaultRecord:dic];
    }
}

/**
 *  根据请求参数获得数据
 *
 *  @param param 请求参数
 *
 *  @return 字典数组
 */
+ (NSArray *)defaultRecordWithParam:(NSDictionary *)param {
    // 1.定义数组
    __block NSMutableArray *dictArray = nil;
    
    // 2.使用数据库
    [_queue inDatabase:^(FMDatabase *db) {
        // 创建数组
        dictArray = [NSMutableArray array];
        
        // accessToken
        NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
        NSString *userName = [userDef objectForKey:CYUserNameKey];
        NSString *password = [userDef objectForKey:CYPasswordKey];
        NSString *access_token = nil;
        if (userName && password) {
            access_token = [password stringByAppendingString:userName];//用户唯一标识
        }else {
            access_token = @"visitor";
        }
        
        FMResultSet *rs = nil;
        if (param[@"createTime"]) { // 如果有since_id
            rs = [db executeQuery:@"select * from t_defaultRecord where access_token = ? and createTime > ? order by createTime desc limit 0,?;", access_token, param[@"createTime"], param[@"count"]];
        }else if (param[@"search"]) {
            rs = [db executeQuery:@"select * from t_defaultRecord where access_token = ? and (name like ? or certificateNo like ? or phone like ?) order by createTime desc limit 0,?;", access_token, param[@"search"], param[@"search"], param[@"search"], param[@"count"]];
        } else if (param[@"idstr"]) {
            rs = [db executeQuery:@"select * from t_defaultRecord where access_token = ? and idstr = ? order by createTime desc limit 0,?;", access_token, param[@"idstr"], param[@"count"]];
        } else { // 如果没有since_id和max_id
            rs = [db executeQuery:@"select * from t_defaultRecord where access_token = ? order by createTime desc limit 0,?;", access_token, param[@"count"]];
        }
        
        while (rs.next) {
            NSData *data = [rs dataForColumn:@"defaultRecord"];
            CYDefaultRecordAO *defr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            [dictArray addObject:defr];
        }
    }];
    
    // 3.返回数据
    return dictArray;
}
@end
